import request from '@/utils/request';
import axios from 'axios';

/**
 * 上传视频
 * @param {Object} data - 包含以下属性的对象:
 *   - size: 文件大小
 *   - md5: 文件的MD5哈希值
 *   - videoName: 文件的名称
 *   - videoTitle: 文件的标题
 *   - videoType: 音视频类型，例如MP4、TS、MOV、MP3、OGG、WAV等
 * @returns {Promise}
 */
export function uploadVodFile(data) {
  return request({
    url: '/common/uploadVodFile',
    method: 'post',
    data: data,
  });
}

// 获取分段文件上传地址
export function getPartFileUploadUrl(data) {
  return request({
    url: '/common/getPartFileUploadUrl',
    method: 'post',
    data,
  });
}

// 确认大文件上传成功
export function confirmUploadBigVodFile(data) {
  return request({
    url: '/common/confirmUploadBigVodFile',
    method: 'post',
    data,
  });
}
/**
 * 上传视频
 */
export function confirmUploadVodFile(data) {
  return request({
    url: '/common/confirmUploadVodFile',
    method: 'post',
    data: data,
  });
}
// 获取播放地址
export function getVideoPlayUrl(data) {
  return request({
    url: '/common/getVideoPlayUrl',
    method: 'post',
    data: data,
  });
}

export function uploadVideo(uploadUrl, file) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('PUT', uploadUrl);
    xhr.setRequestHeader('Content-Type', 'video/mp4');
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response);
      } else {
        reject(xhr.statusText);
      }
    };
    xhr.onerror = () => {
      reject(xhr.statusText);
    };
    xhr.send(file);
  });
}

export function uploadBigVideo(uploadUrl, file, md5) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('PUT', uploadUrl);
    xhr.setRequestHeader('Content-Type', 'application/octet-stream');
    xhr.setRequestHeader('Content-MD5', md5);
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response);
      } else {
        reject(xhr.statusText);
      }
    };
    xhr.onerror = () => {
      reject(xhr.statusText);
    };
    xhr.send(file);
  });
}

export function uploadPutVideo(uploadUrl, file) {
  return new Promise((resolve, reject) => {
    console.log(uploadUrl);
    this.$axios({
      url: uploadUrl,
      method: 'PUT',
      data: file,
      headers: {
        'Content-Type': 'video/mp4',
      },
    }).then((res) => {
      resolve();
      console.log('文件上传成功');
    });
  });
}
